package com.touzbi.hss.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import com.touzbi.hibernate.util.HibernateUtil;
import com.touzbi.hss.beans.Patient;
import com.touzbi.hss.bo.FormBO;
import com.touzbi.hss.dao.AbstractDAOFactory;
import com.touzbi.hss.dao.DAOFactory;

/**
 * Servlet implementation class NewServlet
 */
@WebServlet("/new-patient")
public class NewPatientServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String ADD_PATIENT_JSP = "/WEB-INF/add_patient.jsp";
	private static final String SUCCESS_JSP = "/WEB-INF/add_patient_success.jsp";
	private static final String FORM_ATT = "form";
	private static final String PATIENT_ATT = "patient";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.getServletContext().getRequestDispatcher(ADD_PATIENT_JSP)
				.forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		AbstractDAOFactory daoFactory = new DAOFactory(
				HibernateUtil.getSessionFactory());
		Session session = daoFactory.getSession();
		session.beginTransaction();

		FormBO formBO = new FormBO(daoFactory, req);
		Patient patient = formBO.addPatient(req);

		session.getTransaction().commit();

		req.setAttribute(FORM_ATT, formBO);

		if (formBO.registrationSuccessfull()) {
			req.getServletContext().getRequestDispatcher(SUCCESS_JSP)
					.forward(req, resp);
		} else {
			req.setAttribute(PATIENT_ATT, patient);
			req.getServletContext().getRequestDispatcher(ADD_PATIENT_JSP)
					.forward(req, resp);
		}
	}
}
